
package org.elanfox.intellicommunity.intellicommunityadmin.base.security;

import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author gmw
 * @date 2017-08-06
 */
public class SmAuthenticationProcessingFilter extends UsernamePasswordAuthenticationFilter {
    private static final String METHOD = "POST";
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (!METHOD.equals(request.getMethod())) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        } else {
            String verifyCode = String.valueOf(request.getSession().getAttribute("verifyCode"));
            String requestCode = request.getParameter("verifyCode");

            //开发时就不校验验证码了
//            if (request.getSession().getAttribute(Constant.VERIFY_TAG) != null) {
//                if (StringUtils.isEmpty(verifyCode)
//                        || StringUtils.isEmpty(requestCode)
//                        || !verifyCode.equalsIgnoreCase(requestCode)) {
//                    throw new VerifyCodeException("验证码不正确");
//                }
//            }
            String username = request.getParameter(getUsernameParameter());
            String password = request.getParameter(getPasswordParameter());
            if (username == null) {
                username = "";
            }

            if (password == null) {
                password = "";
            }
            username = username.trim();
            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);

            this.setDetails(request, authRequest);
            return this.getAuthenticationManager().authenticate(authRequest);
        }
    }


}
